package com.example.shushiyunsst.fragment.main.home.child

import android.graphics.Color
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSON
import com.example.library_common.album.utils.Utils
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.IconNodeFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.bean.IconNodeBean
import com.example.shushiyunsst.fragment.main.home.child.bean.IconNodeListBean
import com.example.shushiyunsst.fragment.main.home.child.miner22.Miner22HelperFragment
import com.example.shushiyunsst.util.ICON_NODE
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.example.wallet.utils.selectorIcon
import com.github.mikephil.charting.animation.Easing
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.data.PieData
import com.github.mikephil.charting.data.PieDataSet
import com.github.mikephil.charting.data.PieEntry
import com.github.mikephil.charting.formatter.PercentFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.senon.modularapp.util.JssSpannableString
import ikidou.reflect.TypeBuilder

/**
 * 节点
 * */
@Route(path = ICON_NODE)
class IconNodeFragment : BaseDataBindingFragment<IconNodeFragmentBinding>(), View.OnClickListener {


    override fun layoutId(): Int {
        return R.layout.icon_node_fragment
    }

    private var obj: IconNodeBean? = null

    private var mAdapter: CommAdapter<IconNodeBean.DestoryLogBean>? = null

    private var mIconNodeAdapter: CommAdapter<IconNodeListBean>? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.setTitle(R.string.lian_san_nong)

        val menu = mToolbar.menu
        val nodeIncome = menu.add(Menu.NONE, R.id.temp_id, Menu.NONE, R.string.icon_node_income)
        nodeIncome.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS)

        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }
        mToolbar.setOnMenuItemClickListener {

            when(it?.itemId){
                R.id.temp_id->{
                    start(IconNodeIncomeListFragment.newInstance())
                }
            }

            return@setOnMenuItemClickListener true
        }
        viewBinder.nodeIncomeTitle.text =
            _mActivity.getString(R.string.node_income_title, selectorIcon())

        viewBinder.nodeAllIncomeTitle.text =
            _mActivity.getString(R.string.node_all_income_title, selectorIcon())

        viewBinder.nodeTodayCostTitle.text =
            _mActivity.getString(R.string.node_today_destroy_title, selectorIcon())

        viewBinder.subCostUtilNow.text =
            _mActivity.getString(R.string.sub_cost_util_now, selectorIcon())

        viewBinder.onViewClick = this

        mAdapter = object :
            CommAdapter<IconNodeBean.DestoryLogBean>(_mActivity, R.layout.icon_node_item_fragment) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: IconNodeBean.DestoryLogBean?,
                position: Int
            ) {
                holder?.setText(R.id.countTv, "${item?.totalTxNums}")
                    ?.setText(R.id.title_template, "${item?.desTypeDesc} ${item?.tokenType}")
                    ?.setText(R.id.addAddressTv, "销毁地址 : ${item?.walletAddress}")
            }
        }

        viewBinder.mXGridLayout.setAdapter(mAdapter, lifecycle)
        viewBinder.mXGridLayout.maxItem = obj?.destoryLog?.size ?: 6

        mIconNodeAdapter =
            object : CommAdapter<IconNodeListBean>(_mActivity, R.layout.icon_node_list_fragment) {
                override fun convert(
                    holder: XQuickViewHolder?,
                    item: IconNodeListBean?,
                    position: Int
                ) {
                    holder?.setText(R.id.title, "${item?.title}")
                        ?.setText(R.id.numTv, "${item?.num} (${item?.tokenType})")
                        ?.setText(
                            R.id.discount,
                            JssSpannableString(_mActivity, "${item?.disCount}")
                                .first("${item?.disCount}")
                                .size(8)
                        )
                        ?.setOnClickListener(R.id.takeOrder) {
                            sendTakeOrder(position)
                        }
                }

            }
        viewBinder.mNodeXGridLayout.setAdapter(mIconNodeAdapter, lifecycle)
        val iconNode = Utils.getJsonFromRaw(_mActivity, R.raw.micon_node)
        val build = TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(IconNodeListBean::class.java)
            .endSubType()
            .build()
        val bean: CommonBean<List<IconNodeListBean>> = JSON.parseObject(iconNode, build)
        val data = bean.data
        mIconNodeAdapter?.clear()
        mIconNodeAdapter?.addAll(data)

        initPieChart()

        getNodeInfo()

    }

    private fun getNodeInfo() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
        val map = mapOf(
            "uid" to userInfo?.uid,
            "deviceToken" to deviceTokens
        )
        RestClient.builder()
            .url(R.string.nodeIndex)
            .raw(JSON.toJSONString(map))
            .success {
                parseNodeIndex(it)
            }
            .error { _, msg ->
                normalShortToast(_mActivity,msg)
//                Toast.makeText(_mActivity, msg, Toast.LENGTH_LONG).show()
                onBackPressedSupport()
            }.failure {
                normalShortToast(_mActivity,R.string.get_icon_node_info_failed)
//                Toast.makeText(_mActivity, "获取节点信息失败", Toast.LENGTH_LONG).show()
                onBackPressedSupport()
            }.build().post()
    }

    private fun parseNodeIndex(it: String?) {
        obj = JSON.parseObject(it, IconNodeBean::class.java)
        viewBinder.bean = obj
        mAdapter?.clear()
        mAdapter?.addAll(obj?.destoryLog)

        addPiChartData()

    }

    //认购
    private fun sendTakeOrder(position: Int) {
        val iconNodeListBean = mIconNodeAdapter?.data?.get(position)
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "nodeLevel" to iconNodeListBean?.nodeName,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.buyNode)
            .success {
                Toast.makeText(_mActivity, "购买成功", Toast.LENGTH_SHORT).show()
                getNodeInfo()
                getUserBalanceInfo(_mActivity)
            }
            .error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.failure {
                Toast.makeText(_mActivity, "购买失败", Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun initPieChart() {
        viewBinder.mPieChart.setUsePercentValues(false)
        viewBinder.mPieChart.description.isEnabled = false
        viewBinder.mPieChart.setExtraOffsets(5f, 10f, 5f, 5f)

        viewBinder.mPieChart.dragDecelerationFrictionCoef = 0.95f



        viewBinder.mPieChart.isDrawHoleEnabled = true
        viewBinder.mPieChart.setHoleColor(Color.WHITE)

        viewBinder.mPieChart.setTransparentCircleColor(Color.WHITE)
        viewBinder.mPieChart.setTransparentCircleAlpha(110)

        viewBinder.mPieChart.holeRadius = 58f;
        viewBinder.mPieChart.transparentCircleRadius = 61f;

        viewBinder.mPieChart.rotationAngle = 0f

        // 触摸旋转
        viewBinder.mPieChart.isRotationEnabled = true
        viewBinder.mPieChart.isHighlightPerTapEnabled = true

        // 设置是否显示饼图上的Lable文字
        viewBinder.mPieChart.setDrawEntryLabels(false)

//        //变化监听
//        mPieChart.setOnChartValueSelectedListener(this);


        viewBinder.mPieChart.animateY(1400, Easing.EaseInOutQuad)

        val l: Legend = viewBinder.mPieChart.legend
        l.verticalAlignment = Legend.LegendVerticalAlignment.TOP
//        l.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
        l.orientation = Legend.LegendOrientation.VERTICAL
        l.setDrawInside(false)
        l.xEntrySpace = 7f
        l.yEntrySpace = 0f
        l.yOffset = 0f

        // 输入标签样式
        viewBinder.mPieChart.setEntryLabelColor(Color.BLACK)
        viewBinder.mPieChart.setEntryLabelTextSize(9f)


    }

    private fun addPiChartData() {

        //设置中间文件
        viewBinder.mPieChart.centerText = "${obj?.totalNums22?.toInt()} 人"

        // 数据
        val entries = ArrayList<PieEntry>()
        val fenSi = ((obj?.fensi ?: 0.0).toFloat())
        val chiBi = ((obj?.chibi ?: 0.0).toFloat())
//        val shiMing = ((obj?.shiming ?: 0.0).toFloat())
        entries.add(PieEntry(fenSi, "粉丝（名）"))
        entries.add(PieEntry(chiBi, "有效（名）"))
//        entries.add(PieEntry(shiMing, "实名（名）"))


        //设置数据
        setData(entries)
    }

    //设置数据
    private fun setData(entries: ArrayList<PieEntry>) {
        val dataSet = PieDataSet(entries, "")
        dataSet.sliceSpace = 3f
        dataSet.selectionShift = 5f

        //数据和颜色
        val colors = ArrayList<Int>()
        colors.add(ContextCompat.getColor(_mActivity, R.color.bg_color_16))
        colors.add(ContextCompat.getColor(_mActivity, R.color.bg_color_17))
        colors.add(ContextCompat.getColor(_mActivity, R.color.bg_color_18))
//        for (c in ColorTemplate.VORDIPLOM_COLORS) colors.add(c)
//        for (c in ColorTemplate.JOYFUL_COLORS) colors.add(c)
//        for (c in ColorTemplate.COLORFUL_COLORS) colors.add(c)
//        for (c in ColorTemplate.LIBERTY_COLORS) colors.add(c)
//        for (c in ColorTemplate.PASTEL_COLORS) colors.add(c)
        colors.add(ColorTemplate.getHoloBlue())
        dataSet.colors = colors
        val data = PieData(dataSet)
        data.setValueFormatter(IconNodeFormatter())
//        data.setValueFormatter(PercentFormatter())
        data.setValueTextSize(9f)
        data.setValueTextColor(Color.BLACK)

        viewBinder.mPieChart.data = data
        viewBinder.mPieChart.highlightValues(null)
        //刷新
        viewBinder.mPieChart.invalidate()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.structureAvatar->{
                start(Miner22HelperFragment.newInstance())
            }
            R.id.activeNode -> {
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val deviceTokens = Preference.HOLDER.getCustomAppProfile(CURRENT_DEVICE_TOKEN)
                RestClient.builder()
                    .url(R.string.activeNode)
                    .raw(
                        JSON.toJSONString(
                            mapOf(
                                "uid" to userInfo?.uid,
                                "deviceToken" to deviceTokens
                            )
                        )
                    )
                    .success {
                        getNodeInfo()
                        normalShortToast(_mActivity,R.string.icon_node_avtive)
//                        Toast.makeText(_mActivity, "激活成功", Toast.LENGTH_SHORT).show()
                    }.failure {
                        normalShortToast(_mActivity,R.string.net_work_failed)
//                        Toast.makeText(_mActivity, "网络异常", Toast.LENGTH_SHORT).show()
                    }.error { _, msg ->
                        normalShortToast(_mActivity,msg)
//                        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                    }.build().post()
            }
        }
    }

}